<template>
<view class="page-tickets-choose-sku">
  <basic-nav-bar 
    left-icon="arrowleft" 
    title="选择套餐和人数" 
    statusBar
    :fixed="true">
  </basic-nav-bar>
  <view class="tickets-choose-sku">
    <sku-calendar
      v-model="chooseDate"
      :enabledDates="enabledDates"
      @change="dateChange">
    </sku-calendar>

    <!-- 场次 -->
    <sku-round v-if="roundList && roundList.length" v-model="roundIndex" :roundList="roundList" />

    <!-- 规格与数量 -->
    <sku-number v-if="normList && normList.length" :normList="normList" @change="handleNormChange"/>

    <basic-safe-area />
  </view>

  <!-- 预订按钮 -->
  <view class="next-step-pannel">
    <view class="next-step-btn">
      <view class="price-wrapper">
        <basic-price :price="totalPrice" size="36rpx" weight="600" color="#FF5944" unitColor="#FF5944"/>
        <text class="price-detail-trigger" @click="showPriceDetail = true">费用明细</text>
      </view>
      <basic-button type="primary" borderRadius="0" width="240rpx" height='100%' @click="goNextStep">下一步</basic-button>
    </view>
    <basic-safe-area />
  </view>
  
  <!-- 费用明细 -->
  <basic-bottom-popover
    v-model="showPriceDetail"
    :z-index="1"
    title="费用明细">
    <view class="price-detail-popover-content">
      <sku-price-detail :normList="normList" :totalPrice="totalPrice"/>
      <basic-safe-area />
    </view>
  </basic-bottom-popover>
</view>
</template>
<script>
import skuCalendar from '../../../components/sku-calendar'
import skuNumber from '../../../components/sku-number'
import skuRound from '../../../components/sku-round'
import skuPriceDetail from '../../../components/sku-price-detail'
import storage from 'utils/helper/storage'
import {sortByKey} from 'utils/helper/common'
import {dateFormat} from 'utils/helper/date-handle'
import {decodeQueryObject} from 'utils/helper/query'
import {cent2Yuan} from '@/filter/filters'
import store from '@/store'
import math from 'utils/helper/math'
import sdk from 'sdk'
import {getBookCheck} from 'api'
import modal from 'utils/helper/modal'

export default {
  name: 'page-tickets-choose-sku',
  components: { skuCalendar, skuNumber, skuRound, skuPriceDetail },

  data() {
    return {
      normList: [],
      roundIndex: 0, // 场次
      roundList: [], // 场次列表
      inventoryReleases: [],
      chooseDate: '', // dateFormat(new Date())

      showCalendar: true, // 是否显示日历
      showPriceDetail: false // 是否显示价格明细
    }
  },

  computed: {
    enabledDates() {
      let result = {}
      this.inventoryReleases.forEach(item => {
        result[item.startDate] = '￥' + cent2Yuan(item.price)
      })

      return result
    },
    totalPrice() {
      return this.normList.reduce((total, item, index) => {
        total +=  math.multiply(item.price, item.chooseNum) 

        return total
      }, 0)
    }
  },

  onLoad(query) {
    this.getData()
		const options = decodeQueryObject(query)
    const { mToken } = options
		if(mToken) store.commit('SAVE_TOKEN', { token: mToken })
  },

  methods: {
    getData() {
      let cacheTicketInfo = storage.get('ticket_choose_sku')

      if (!cacheTicketInfo || !cacheTicketInfo.poiCode || !cacheTicketInfo.poiDetail || !cacheTicketInfo.skuDetail) {
        uni.showToast({
          title: '抱歉，获取门票信息失败',
          icon: 'none',
          duration: '2000'
        })

        setTimeout(() => {sdk.navigateBack()}, 2000)
        return
      }

      // 日期价格列表
      this.skuDetail = cacheTicketInfo.skuDetail
      this.inventoryReleases = cacheTicketInfo.skuDetail.inventoryReleases
      
      // 场次列表
      this.roundList = cacheTicketInfo.skuDetail.timeSlots || []

      // 规格数量
      this.normList = []
    },

    dateChange(val) {
      this.chooseDate = val.fulldate

      this.showCalendar = false

      this.updateNormList()
    },

    /**
     * 更新sku列表
     */
    updateNormList() {
      if (!this.chooseDate) {
        this.normList = []
        return
      }

      let dateStr = this.chooseDate + ' 00:00:00'
      let targetInventory = this.inventoryReleases.find(item => item.startDate === dateStr)

      if (targetInventory && targetInventory.price) {
        let normItem = {
          name: '门票',
          remark: this.skuDetail.remark,
          code: this.skuDetail.skuCode,
          maxNum: this.skuDetail.maxBookNum, // 限购数（该值用来显示“该商品限购x件”，所以，需要为maxBookNum的原始值）
          maxBookNum: this.skuDetail.maxBookNum,
          minBookNum: this.skuDetail.minBookNum,
          inventoryNum: targetInventory.inventoryNum,
          price: targetInventory.price,
          chooseNum: this.skuDetail.minBookNum || 1 // 默认选择1个
        }
        // [mark]从ubd抄过来的逻辑
        // inventoryNum :-1 不限制库存  0: 库存为0
        // maxBookNum :-1 不可订  0: 不限制最大可订
        if(normItem.inventoryNum > 0){ //限制库存
            if(normItem.maxBookNum === 0 || normItem.inventoryNum < normItem.maxBookNum){ //不限制最大可定 或 最大可订超过库存
              normItem.maxBookNum = normItem.inventoryNum
            }
        } else if (normItem.inventoryNum < 0) { //不限制库存
          normItem.inventoryNum = 999999
          if(normItem.maxBookNum > 0 && normItem.minBookNum && normItem.maxBookNum < normItem.minBookNum){ //最小可定大于最大可定，不可订
            normItem.maxBookNum = -1
          } else if (normItem.maxBookNum === 0) { // 不限制最大可订
            normItem.maxBookNum = 999999
          }
        } else { // 无库存
          normItem.maxBookNum = -1
        }
        
        // 初始化选择数
        if(normItem.minBookNum) {
          normItem.chooseNum = normItem.minBookNum
        }

        if(normItem.maxBookNum < 0 ){
          return
        }

        this.normList = [normItem]
      }
    },
    goNextStep() {
      // 日期检查
      if (!this.chooseDate) {
        modal.toast('请先选择日期')
        return
      }

      // 规格检查
      let selectedNorm = this.normList.filter((norm) => norm.chooseNum > 0)

      if (selectedNorm.length <= 0) {
        modal.toast('请选择规格')
        return
      }

      // 获取预订参数
      let round = this.roundList.length ? this.roundList[this.roundIndex].name : ''
      let bookCheckProductSearchs = selectedNorm.map(norm => {
        let item = {
          code: norm.code,
          num: norm.chooseNum
        }

        if (round) {
          item.specRound = round
        }

        return item
      })

      // 检查是否可订
      let bookInfo = {
        checkin: this.chooseDate,
        bookCheckProductSearchs
      }
      getBookCheck(bookInfo).then(res => {
        // 本地缓存sku数据
        storage.set('fill_order_sku', bookInfo)
        sdk.navigateTo({
          url: '/packageOrder/pages/fill-order-info/index'
        })
      }).catch(_ => {})
    },

    /**
     * 修改规格数量（小程序无法在子组件修改父组件传入的对象属性）
     */
    handleNormChange(e = {}) {
      let {value, index} = e

      this.normList[index].chooseNum = value
    }
  }
}
</script>
<style lang="less">
@booking_height: 100rpx;
.page-tickets-choose-sku {
  background: #ffffff;
  min-height: 100vh;

  .tickets-choose-sku {
    width: 100%;
    margin-bottom: @booking_height;
  }
  
  /deep/ .sku-choose-block {
    background-color: #fff;
    padding: 30rpx;
    border-bottom: 1rpx solid @border_color;

    .sku-choose-block-title {
      font-size: 32rpx;
      font-weight: 600;
      height:46rpx;
      line-height:46rpx;
    }
  }

  .next-step-pannel {
    position: fixed;
    z-index: 2;
    bottom: 0;
    width: 100%;
    background: #fff;
    box-shadow: 0 0 14rpx 0 rgba(204, 204, 204, 0.5);

    .next-step-btn {
      .flex;
      height: @booking_height;
    }
    .price-wrapper {
      .flex-1;
      .flex;
      .flex-middle;

      margin: 0 36rpx;
    }

    .price-detail-trigger {
      margin-left: 20rpx;

      font-size: 24rpx;
      color: @font_desc_color;
      text-decoration: underline;
    }
  }

  .price-detail-popover-content {
    position: relative;
    z-index: 0;
    margin-bottom: @booking_height;
  }
}

</style>